/* YAJSTL.js 
 * Yet Another JS Template Library
 * 
 * Include your templates via <script type="text/x-template" title="<name>"></script>
 */
if (typeof jQuery !== 'undefined') {
    jQuery.LMF = jQuery.LMF || {};
    jQuery.LMF.templates = {
        _list: [],
        create: function(tname, template) {
            var t = {name: tname, content: template, fill: function(options) {
                var tpl = this.content || "";
                for (key in options) {
                    var val = options[key];
                    if (val === undefined) {
                    	val = "";
                    } else if (typeof val.html === 'function') {
                        val = jQuery("<div>").append(val.clone()).html();
                    }
                    tpl = tpl.replace(new RegExp('\\$\\{'+ key + '\\}', 'g'), val);
                }
                return tpl;
            }};
            this._list[tname] = t;
            return t;
        },
        load: function(tname) {
        	if (tname !== undefined) {
        		if (this._list[tname] !== undefined) {
        			return this._list[tname];
        		} else {
        		    var tscr = jQuery('script[type="text/x-template"][title="' + tname + '"]');
        		    this._loadRemoteTemplate(tscr);
        		    var content = tscr.html();
        			return this.create(tname, content);
        		}
        	} else {
        		var self = this;
        		jQuery('script[type="text/x-template"]').each(function(i){
        		    var tpl = jQuery(this);
        			// self.create(tpl.attr('title'), tpl.html());
        		    self._loadRemoteTemplate(tpl);
        		});
        		return undefined;
        	}
        },
        fill: function(tname, options) {
            return this.load(tname).fill(options);
        },
        _loadRemoteTemplate: function(tscr) {
		    if (tscr && tscr.attr('src') !== undefined && tscr.attr('loaded') !== 'true') {
		        // load external template
		        var loader = new XMLHttpRequest();
		        loader.open('GET', tscr.attr('src'), false);
		        loader.send();
		        if (loader.responseText !== null) {
		            tscr.html(loader.responseText);
		            tscr.attr('loaded', 'true');
		            if (tscr.attr('title') === undefined) {
		            	tscr.attr('title', tscr.attr('src').replace(/^.*\/(.*?)(\.(js|tpl))?$/, "$1"));
		            }
		        }
		    }
		    return tscr;
        } 
    };
}